package com.bdqn.crm.controller;

import com.bdqn.crm.pojo.SysUser;
import com.bdqn.crm.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class IndexController {

    @Resource
    private SysUserService sysUserService;

    //跳转到login.html页面
    /*@RequestMapping(value = "/login")
    public String login(){
        return "login";
    }*/

    @RequestMapping(value = "/login")
    public String index(){
        return "login";
    }



    @RequestMapping(value = "/doLogin")
    public String doLogin(String usrName,    String usrPassword, Model model, HttpSession session){
        try{
            UsernamePasswordToken token = new UsernamePasswordToken(usrName,usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);   //认证、登录
            //认证(登录)成功
            SysUser user = (SysUser) subject.getPrincipal();
            if (user !=null){
                session.setAttribute("loginUser",user);
                return "redirect:main";//建议重定向
            }
        }  catch (UnknownAccountException | IncorrectCredentialsException e){
            model.addAttribute("message","用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e){
            model.addAttribute("message","用户被禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e){
            model.addAttribute("message","认证异常，登录失败！");
            return "login";
        }
        return "login";
    }

    @RequestMapping(value = "/main")
    public String main(){
        return "main";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();//Shiro注销
        return "redirect:/login";//建议重定向，保证删除Cookie
    }

    @RequestMapping(value = "/403")
    public String unauthorized(){
        return "403";
    }
}
